function recordPreview(){
    var story = $("#id_story").val();
    //window.open("/admin/news/record/preview/?story="+story, "Preview", "status=1, width=690, height=500, scrollbars=1");
	var win = window.open('', 'Preview', "status=1, width=690, height=450, scrollbars=1");
    $.post("/admin/news/record/preview/", {story: story}, function(response){
    	win.document.write(response);
    });
}

function showColorPicker(){
	$(".jColorSelect").show();
}

function replaceIt(txtarea, newtxt) {
  $(txtarea).val(
        $(txtarea).val().substring(0, txtarea.selectionStart)+
        newtxt+
        $(txtarea).val().substring(txtarea.selectionEnd)
   );  
}

$(document).click(function(){
	if($(".jColorSelect").is(":visible")){
		$(".jColorSelect").hide();
	}
});

var imagesManager = {
    recordID: null,
    checkAll: function(){
        if($("#checkImagesList").is(":checked")){
            $("#imagesList input[type=checkbox]").attr("checked", "checked");
        } else {
            $("#imagesList input[type=checkbox]").removeAttr("checked");
        }
    },
    show: function(){
        this.reload_list();
        $("#imagesManagerDialog").dialog({
            title: 'Управление изображениями',
            modal: true,
            width: 500,
            height: 500
        });
    },
    reload_list: function(){
        var data = {};
        if(imagesManager.recordID) data = {'pk': imagesManager.recordID};
        $.post("/admin/files/list/", data, function(response){
            imagesManager.images_list = {};
            var images_list = $("<table/>");
            for(var key in response.images){
                var image = response.images[key];
                imagesManager.images_list[image.id] = image;
                var tr = $("<tr/>")
                    .append("<td width='10'><input type='checkbox' value='"+image.id+"'></td>")
                    .append("<td>"+image.image+"</td>");
                if(image.record){
                    tr.addClass("used");
                }
                $(images_list).append(tr);
            }
            $("#imagesManagerDialog #imagesList").html($(images_list));
        });
    },
    insert_images: function(){
        $("#imagesManagerDialog #imagesList input:checked").each(function(){
            if(imagesManager.images_list[$(this).val()].thumbnail){
                $(".bbeditor").val($(".bbeditor").val()+"[thumb]"+imagesManager.images_list[$(this).val()].url+"[/thumb]\n");
            }else{
                $(".bbeditor").val($(".bbeditor").val()+"[img]"+imagesManager.images_list[$(this).val()].url+"[/img]\n");
            }
        });
    },
    delete_images: function(){
        var ids = [];
        $("#imagesManagerDialog #imagesList input:checked").each(function(){
            ids.push($(this).val());
        });
        $.post("/admin/files/delete/", {'ids': ids.join(',')}, function(response){
            imagesManager.reload_list();
        });
    }
}

$(document).ready(function(){
    $('.bbeditor').markItUp(mySettings);
    $('#imagesManagerDialog #accordion').accordion();
    var settings = {
        flash_url : "/static/scripts/swfupload/swfupload.swf",
        flash9_url : "/static/scripts/swfupload/swfupload_fp9.swf",
        upload_url: "/admin/files/upload/",
        file_size_limit : "100 MB",
        file_types : "*.png;*.gif;*.jpg;*.jpeg;*.bmp",
        file_types_description : "Images Files",
        file_upload_limit : 300,
        file_queue_limit : 0,
        custom_settings : {
            progressTarget : "fsUploadProgress",
            cancelButtonId : "btnCancel"
        },
        debug: false,
        // Button settings
        button_image_url: "/static/scripts/swfupload/btn.png",
        button_width: "112",
        button_height: "21",
        button_placeholder_id: "spanButtonPlaceHolder",

        // The event handler functions are defined in handlers.js
        swfupload_preload_handler : preLoad,
        swfupload_load_failed_handler : loadFailed,
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_start_handler : uploadStart,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,
        queue_complete_handler : queueComplete	// Queue plugin event
    };
    swfu = new SWFUpload(settings);
});

$.fn.extend({
    insertAtCaret: function(myValue) {
        if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
        }
        else if (this.selectionStart || this.selectionStart == '0') {
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += myValue;
            this.focus();
        }
    }
})
